package com.sojson.util.encryption;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.sojson.constant.Constant;
import com.sojson.util.encryption.enums.EEncryptionType;

/**
 * MD5工具类
 * 
 * @author liu
 * @date 2020-09-04
 */
public class Md5Util {

    private static final MessageDigest md = getMd5();

    /**
     * 加密
     * 
     * @param content
     * @return
     * @throws IOException 
     */
    public static String encryption(String content) throws IOException {
        return encryption(content.getBytes(Constant.DEFAULT_ENCODING));
    }

    /**
     * 加密
     * 
     * @param content
     * @return
     */
    public static String encryption(byte[] content) {
        byte[] array = md.digest(content);
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }

    /**
     * 加密并转为大写
     * 
     * @param content
     * @return
     * @throws IOException 
     */
    public static String encryptionToUpperCase(String content) throws IOException {
        return encryption(content).toUpperCase();
    }

    /**
     * 加密并转为大写
     * 
     * @param content
     * @return
     */
    public static String encryptionToUpperCase(byte[] content) {
        return encryption(content).toUpperCase();
    }

    /**
     * 获取MD5
     * 
     * @return
     */
    private static MessageDigest getMd5() {
        try {
            return MessageDigest.getInstance(EEncryptionType.MD5.getType());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

}